package cn.edu.xmu.oomall.customer.dao;

import cn.edu.xmu.javaee.core.util.CloneFactory;
import cn.edu.xmu.oomall.customer.dao.bo.Coupon;
import cn.edu.xmu.oomall.customer.mapper.jpa.CouponPoMapper;
import cn.edu.xmu.oomall.customer.mapper.po.CouponPo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Suave
 * @date 2024/12/20
 */
@Repository
@RequiredArgsConstructor
public class CouponDao {
    private final CouponPoMapper couponPoMapper;
    /**
     * 通过用户id和是否使用查找优惠券
     * @param id 用户id
     * @param used 是否使用
     * @param page 页码
     * @param pageSize 每页数量
     * @return 优惠券列表
     */
    public List<Coupon> findByCustomerIdAndUsed(Long id, Byte used, Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        Page<CouponPo> couponPoPage = couponPoMapper.findByCustomerIdAndUsed(id, used, pageable);
        if(couponPoPage.isEmpty()) {
            return new ArrayList<>();
        }else {
            return couponPoPage.get().map(po -> CloneFactory.copy(new Coupon(), po)).toList();
        }
    }

    /**
     * 通过活动id和用户id查找优惠券
     * @param activityId 活动id
     * @param customerId 用户id
     * @return 优惠券
     */
    public Coupon findByActivityIdAndCustomerId(Long activityId, Long customerId) {
        Optional<CouponPo> couponPo = couponPoMapper.findByActivityIdAndCustomerId(activityId, customerId);
        return couponPo.map(po -> CloneFactory.copy(new Coupon(), po)).orElse(null);
    }

    /**
     * 插入优惠券
     * @param coupon 优惠券
     * @return 优惠券
     */
    public Coupon insert(Coupon coupon) {
        CouponPo couponPo = CloneFactory.copy(new CouponPo(), coupon);
        couponPoMapper.save(couponPo);
        coupon.setId(couponPo.getId());
        return coupon;
    }

    /**
     * 更新优惠券
     * @param coupon 优惠券
     */
    public void save(Coupon coupon) {
        couponPoMapper.save(CloneFactory.copy(new CouponPo(), coupon));
    }
}
